package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.RecZmPaperInsideManagement;
import com.ruoyi.system.domain.RecZmPaperManagement;
import com.ruoyi.system.domain.RecordArchivesBook;
import com.ruoyi.system.mapper.RecZmPaperInsideManagementMapper;
import com.ruoyi.system.mapper.RecZmPaperManagementMapper;
import com.ruoyi.system.service.IRecZmPaperInsideManagementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.validation.Validator;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 专门档案 卷内管理Service业务层处理
 *
 * @author yzf
 * @date 2022-06-03
 */
@Service
public class RecZmPaperInsideManagementServiceImpl implements IRecZmPaperInsideManagementService {
    @Autowired
    protected Validator validator;
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RecZmPaperInsideManagementMapper recZmPaperInsideManagementMapper;
    @Autowired
    private RecZmPaperManagementMapper zmPaperManagementMapper;

    @Override
    @Transactional
    public String importFile(List<RecZmPaperInsideManagement> fileList, String operName) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        if (CollUtil.isEmpty(fileList)) {
            throw new ServiceException("导入文件数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecZmPaperInsideManagement file : fileList) {
            try {
                BeanValidators.validateWithException(validator, file);
                file.setCreateBy(operName);
                this.insertRecZmPaperInsideManagement(file);
                successNum++;
                successMsg.append("<br/>" + successNum + "、文件 " + file.getTitle() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、文件 " + file.getTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询专门档案 卷内管理
     *
     * @param id 专门档案 卷内管理主键
     * @return 专门档案 卷内管理
     */
    @Override
    public RecZmPaperInsideManagement selectRecZmPaperInsideManagementById(String id) {
        RecZmPaperInsideManagement rmt = recZmPaperInsideManagementMapper.selectRecZmPaperInsideManagementById(id);
        if (ObjectUtil.isNotEmpty(rmt)) {
            //专门档案 案卷管理对象
            rmt.setZmPaperManagementMap(zmPaperManagementMapper.selectZmPaperManagementByIdMap(rmt.getParentId()));
        }
        return rmt;
    }

    /**
     * 查询专门档案 卷内管理列表
     *
     * @param recZmPaperInsideManagement 专门档案 卷内管理
     * @return 专门档案 卷内管理
     */
    @Override
    public List<RecZmPaperInsideManagement> selectRecZmPaperInsideManagementList(RecZmPaperInsideManagement recZmPaperInsideManagement) {
        return recZmPaperInsideManagementMapper.selectRecZmPaperInsideManagementList(recZmPaperInsideManagement);
    }

    @Override
    public List<Map<String, Object>> selectlistByName(RecZmPaperInsideManagement recZmPaperInsideManagement) {
        return recZmPaperInsideManagementMapper.selectlistByName(recZmPaperInsideManagement);
    }

    /**
     * 新增专门档案 卷内管理
     *
     * @param recZmPaperInsideManagement 专门档案 卷内管理
     * @return 结果
     */
    @Override
    public int insertRecZmPaperInsideManagement(RecZmPaperInsideManagement recZmPaperInsideManagement) {
        recZmPaperInsideManagement.setFileNumber(getFileNumber(recZmPaperInsideManagement));
        recZmPaperInsideManagement.setCreateTime(DateUtils.getNowDate());
        recZmPaperInsideManagement.setCreateBy(SecurityUtils.getUsername());
        return recZmPaperInsideManagementMapper.insertRecZmPaperInsideManagement(recZmPaperInsideManagement);
    }

    private String getFileNumber(RecZmPaperInsideManagement recZmPaperInsideManagement) {
        //档案号生成   全宗号-目录号-案卷号-顺序号
        //全宗号
        String fullAncestor = recZmPaperInsideManagement.getFullAncestor();
        if (StrUtil.isEmpty(fullAncestor)) {
            throw new GlobalException("全宗号不能空,请按规则填写");
        }
        //目录号
        String directoryNumber = recZmPaperInsideManagement.getDirectoryNumber();
        if (StrUtil.isEmpty(directoryNumber)) {
            throw new GlobalException("目录号不能空,请按规则填写");
        }
        //案卷号
        String caseNumber = recZmPaperInsideManagement.getCaseNumber();
        if (StrUtil.isEmpty(caseNumber)) {
            throw new GlobalException("案卷号不能空,请按规则填写");
        }

        //顺序号
        String sequenceNumber = recZmPaperInsideManagement.getSequenceNumber();
        if (StrUtil.isEmpty(sequenceNumber)) {
            throw new GlobalException("顺序号不能空,请按规则填写");
        }
        StringBuilder stb = new StringBuilder();
        stb.append(fullAncestor).append("-");
        stb.append(directoryNumber).append("-");
        stb.append(caseNumber).append("-");
        stb.append(sequenceNumber);
        return stb.toString();
    }

    @Override
    public List<RecordArchivesBook> selectlistBook(RecZmPaperInsideManagement recZmPaperInsideManagement) {
        List<Map<String, Object>> list = recZmPaperInsideManagementMapper.selectlistBook(recZmPaperInsideManagement);
        return getRecordArchivesBookList(list);
    }

    public List<RecordArchivesBook> getRecordArchivesBookList(List<Map<String, Object>> list) {
        List<RecordArchivesBook> reList = CollUtil.newArrayList();
        if (CollUtil.isEmpty(list)) {
            return reList;
        }
        RecordArchivesBook reac = null;
        Date date = null;
        String ps = null;
        for (Map<String, Object> map : list) {
            reac = new RecordArchivesBook();
            reac.setArchiveClassifiNum(Convert.toStr(map.get("classification_number")));
            reac.setArchiveFileNum(Convert.toStr(map.get("file_number")));
            reac.setCaseFileTitle(Convert.toStr(map.get("file_title")));
            reac.setArchiveCode(Convert.toStr(map.get("institution")));
            reac.setMiniatureNum(Convert.toStr(map.get("miniature")));
            reac.setPersonLiable(Convert.toStr(map.get("responsible_person")));
            ps = Convert.toStr(map.get("starting_time"));
            if (StrUtil.isNotEmpty(ps)) {
                date = DateUtils.parseDate(ps);
                reac.setCompilationDate(date);
            }
            reac.setStorageTime(Convert.toStr(map.get("storage_time")));
            ps = Convert.toStr(map.get("dense"));
            if (StrUtil.isNotEmpty(ps)) {
                reac.setSecretLevel(DictUtils.getDictLabel("original_level", ps));
            }
            reac.setObjStr3(Convert.toStr(map.get("case_number")));
            reac.setObjStr4(Convert.toStr("nick_name"));
            reList.add(reac);
        }

        return reList;
    }

    /**
     * 修改专门档案 卷内管理
     *
     * @param recZmPaperInsideManagement 专门档案 卷内管理
     * @return 结果
     */
    @Override
    public int updateRecZmPaperInsideManagement(RecZmPaperInsideManagement recZmPaperInsideManagement) {
        recZmPaperInsideManagement.setUpdateTime(DateUtils.getNowDate());
        recZmPaperInsideManagement.setUpdateBy(SecurityUtils.getUsername());
        return recZmPaperInsideManagementMapper.updateRecZmPaperInsideManagement(recZmPaperInsideManagement);
    }

    /**
     * 批量删除专门档案 卷内管理
     *
     * @param ids 需要删除的专门档案 卷内管理主键
     * @return 结果
     */
    @Override
    public int deleteRecZmPaperInsideManagementByIds(String[] ids) {
        return recZmPaperInsideManagementMapper.deleteRecZmPaperInsideManagementByIds(ids);
    }

    /**
     * 删除专门档案 卷内管理信息
     *
     * @param id 专门档案 卷内管理主键
     * @return 结果
     */
    @Override
    public int deleteRecZmPaperInsideManagementById(String id) {
        return recZmPaperInsideManagementMapper.deleteRecZmPaperInsideManagementById(id);
    }

    /**
     * 批量文件上传 卷内管理信息
     *
     * @param
     * @return 结果
     */
    @Override
    public int upLoadMultFile(RecZmPaperInsideManagement recZmPaperInsideManagement) {
        int res = 0;
        String[] strs = recZmPaperInsideManagement.getObjStr11().split(",");
        try {
            for(int i=0; i<strs.length; i++){
                System.out.println(strs[i]);
                // 截取最后一次出现.号和最后一个出现-号的字符。比如xxx-001.pdf,截取的是001
                String num = strs[i].substring(strs[i].lastIndexOf("-")+1, strs[i].lastIndexOf("."));
                res = res + mult(recZmPaperInsideManagement.getParentId(), num, strs[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    private int mult(String parentId, String num, String path){
        int res = 0;
        RecZmPaperInsideManagement recZmPaperInsideManagement = recZmPaperInsideManagementMapper.getMultBy(parentId, num);
        if(recZmPaperInsideManagement != null && StrUtil.isNotEmpty(recZmPaperInsideManagement.getObjStr11())){
            String paths = recZmPaperInsideManagement.getObjStr11() + "," + path;
            recZmPaperInsideManagement.setObjStr11(paths);
            res = recZmPaperInsideManagementMapper.updateRecZmPaperInsideManagement(recZmPaperInsideManagement);
        }else if(recZmPaperInsideManagement != null && StrUtil.isEmpty(recZmPaperInsideManagement.getObjStr11())){
            recZmPaperInsideManagement.setObjStr11(path);
            res = recZmPaperInsideManagementMapper.updateRecZmPaperInsideManagement(recZmPaperInsideManagement);
        }
        return res;
    }

    @Override
    @Transactional
    public int updateArchivesApplyByIds(String[] Ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : Ids) {
            RecZmPaperInsideManagement recordArchives = new RecZmPaperInsideManagement();
            recordArchives.setId(id);
            recordArchives.setObjStr1("1"); //申请状态字段，1：申请
            RecZmPaperInsideManagement recordArchivesOld = this.selectRecZmPaperInsideManagementById(id);
            if ("0".equals(recordArchivesOld.getObjStr1()) || "3".equals(recordArchivesOld.getObjStr1())) { // 未申请或拒绝状态，可申请
                int res = this.updateRecZmPaperInsideManagement(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作未申请和审批拒绝的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesApprove(String[] ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : ids) {
            RecZmPaperInsideManagement recordArchives = new RecZmPaperInsideManagement();
            recordArchives.setId(id);
            recordArchives.setObjStr1("2"); //申请状态字段,2：通过
            RecZmPaperInsideManagement recordArchivesOld = this.selectRecZmPaperInsideManagementById(id);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = this.updateRecZmPaperInsideManagement(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesReject(String[] ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : ids) {
            RecZmPaperInsideManagement recordArchives = new RecZmPaperInsideManagement();
            recordArchives.setId(id);
            recordArchives.setObjStr1("3"); //申请状态字段，3：拒绝
            RecZmPaperInsideManagement recordArchivesOld = this.selectRecZmPaperInsideManagementById(id);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = this.updateRecZmPaperInsideManagement(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    public List<RecZmPaperInsideManagement> RecZmPaperInsideManagementListBy(String parentId) {

        return recZmPaperInsideManagementMapper.recZmPaperInsideManagementListByParentId(parentId);
    }

    @Override
    public File selectRecordFileExport(String archivesId) {
        List<RecZmPaperInsideManagement> insideList = this.RecZmPaperInsideManagementListBy(archivesId);
        if (CollUtil.isNotEmpty(insideList)) {
            List<File> files = CollUtil.newArrayList();
            File f = null;
            String[] filepathArr = null;
            String[] imagespathArr = null;
            for (RecZmPaperInsideManagement rm : insideList) {
                //文件存储路径
                String filePath = rm.getObjStr11();
                if (StrUtil.isNotEmpty(filePath)) {
                    filepathArr = filePath.split(",");
                    for (String s : filepathArr) {
                        filePath = RuoYiConfig.getProfile() + File.separator + s.replace("/profile", "");
                        f = new File(filePath);
                        files.add(f);
                        //   System.out.println(filePath);
                    }
                }
                //图片存储路径
                String imgpath = rm.getObjStr12();
                if (StrUtil.isNotEmpty(imgpath)) {
                    imagespathArr = imgpath.split(",");
                    for (String s : imagespathArr) {
                        filePath = RuoYiConfig.getProfile() + File.separator + s.replace("/profile", "");
                        f = new File(filePath);
                        files.add(f);
                    }
                }
            }
            List<Map<String, Object>> excellist = CollUtil.newArrayList();
            //表格
           /* File excelFile = HutoolExcelUtiles.RecordFileExport(JSONArray.parseArray(JSONObject.toJSONString(list)));
            files.add(excelFile);*/
            //生成zip
            String zipPath = RuoYiConfig.getZipPath() + archivesId + "_案卷包" + IdUtil.getSnowflake().nextIdStr() + ".zip";
            File[] zipfiles = ArrayUtil.toArray(files, File.class);

            File file = ZipUtil.zip(FileUtil.file(zipPath), false, zipfiles);
            //   System.out.println(fres.getAbsoluteFile());
            return file;
        }
        return null;
    }
}
